package com.muyu.common.core.utils.file;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Objects;

import static com.muyu.common.core.constant.FileConstants.*;

/**
 * 文件类型工具类
 *
 * @author muyu
 */
public class FileTypeUtils {
    /**
     * 获取文件类型
     * <p>
     * 例如: muyu.txt, 返回: txt
     *
     * @param file 文件名
     *
     * @return 后缀（不含".")
     */
    public static String getFileType (File file) {
        if (null == file) {
            return StringUtils.EMPTY;
        }
        return getFileType(file.getName());
    }

    /**
     * 获取文件类型
     * <p>
     * 例如: muyu.txt, 返回: txt
     *
     * @param fileName 文件名
     *
     * @return 后缀（不含".")
     */
    public static String getFileType (String fileName) {
        int separatorIndex = fileName.lastIndexOf(".");
        if (separatorIndex < 0) {
            return "";
        }
        return fileName.substring(separatorIndex + 1).toLowerCase();
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     *
     * @return 后缀名
     */
    public static String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }

    /**
     * 获取文件类型
     *
     * @param photoByte 文件字节码
     *
     * @return 后缀（不含".")
     */
    public static String getFileExtendName (byte[] photoByte) {
        String strFileExtendName = "JPG";
        if ((photoByte[ZERO_INDEX] == PHOTO_BYTE_GIF_ZERO) && (photoByte[ONE_INDEX] == PHOTO_BYTE_GIF_ONE) && (photoByte[TWO_INDEX] == PHOTO_BYTE_GIF_TWO) && (photoByte[THREE_INDEX] == PHOTO_BYTE_GIF_THREE)
                && ((photoByte[FOUR_INDEX] == PHOTO_BYTE_GIF_FOUR) || (photoByte[FOUR_INDEX] == PHOTO_BYTE_GIF_FOUR_OR)) && (photoByte[FIVE_INDEX] == PHOTO_BYTE_GIF_FIVE)) {
            strFileExtendName = "GIF";
        } else if ((photoByte[SIX_INDEX] == PHOTO_BYTE_JPG_SIX) && (photoByte[SEVEN_INDEX] == PHOTO_BYTE_JPG_SEVEN) && (photoByte[EIGHT_INDEX] == PHOTO_BYTE_JPG_EIGHT) && (photoByte[NINE_INDEX] == PHOTO_BYTE_JPG_NINE)) {
            strFileExtendName = "JPG";
        } else if ((photoByte[ZERO_INDEX] == PHOTO_BYTE_BMP_ZERO) && (photoByte[ONE_INDEX] == PHOTO_BYTE_BMP_ONE)) {
            strFileExtendName = "BMP";
        } else if ((photoByte[ONE_INDEX] == PHOTO_BYTE_PNG_ONE) && (photoByte[TWO_INDEX] == PHOTO_BYTE_PNG_TWO) && (photoByte[THREE_INDEX] == PHOTO_BYTE_PNG_THREE)) {
            strFileExtendName = "PNG";
        }
        return strFileExtendName;
    }
}
